# leetcdoe 112 路径总和

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        # 遍历所有路径，当和相加等于目标值，返回True
        # 遍历完都没有等于目标值，则返回False
        if not root:
            return False
        path = []
        self.result = False
        def get_path(node):
            path.append(node.val)
            if (not node.left) and (not node.right):
                if sum(path) == targetSum:
                    self.result = True
            if node.left:
                get_path(node.left)
                path.pop()
            if node.right:
                get_path(node.right)
                path.pop()
        get_path(root)
        return self.result
